package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl.object;

import com.fasterxml.jackson.databind.JsonNode;
import com.iwhalecloud.citybrain.flow.platform.manager.application.utils.JsonUtils;
import com.iwhalecloud.citybrain.flow.platform.manager.common.ConstanceVariable;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.object.ProcessObjectMetaVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowObjectRepository;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.Objects;

/**
 * @author lich
 * @date 2021/11/15
 */
public abstract class SaveObjectMetaAbstractProcessor {

    @Autowired
    private FlowObjectRepository flowObjectRepository;

    protected void saveObjectMeta(JsonNode modelJson, String flowCode, String deployId) {
        JsonNode modelProperties = modelJson.get("properties");
        if (Objects.isNull(modelProperties)) {
            return;
        }
        JsonNode objectMeta = modelProperties.get(ConstanceVariable.OBJECT_META);
        if (Objects.isNull(objectMeta) || objectMeta.size()==0) {
            return;
        }

        // nodeCode如果为空说明在flow上
        String nodeCode = getValueFromPropertiesAsStr(modelProperties, ConstanceVariable.OVERRIDE_ID);

        persistentDeployWithObjectMeta(objectMeta, deployId, flowCode, nodeCode);

    }

    private void persistentDeployWithObjectMeta(JsonNode objectMetaNode, String deployId, String flowCode,
        String nodeCode) {
        ProcessObjectMetaVo processObjectMetaVo = new ProcessObjectMetaVo();
        processObjectMetaVo.setDeployId(deployId);

        Date d = new Date();
        processObjectMetaVo.setGmtCreate(d);
        processObjectMetaVo.setGmtModified(d);

        String objectMetaCode = getValueFromPropertiesAsStr(objectMetaNode, "code");
        processObjectMetaVo.setObjectMetaCode(objectMetaCode);

        int objectMetaVersion = getValueFromPropertiesAsInt(objectMetaNode, "version");
        processObjectMetaVo.setObjectMetaVersion(objectMetaVersion);

        processObjectMetaVo.setObjectMetaJson(JsonUtils.toJson(objectMetaNode));

        processObjectMetaVo.setFlowCode(flowCode);
        processObjectMetaVo.setNodeCode(nodeCode);

        flowObjectRepository.saveProcessWithObjectMeta(processObjectMetaVo);

    }

    private static String getValueFromPropertiesAsStr(JsonNode modelProperties, String key) {
        JsonNode jsonNode = modelProperties.get(key);
        return jsonNode == null ? null : jsonNode.textValue();
    }

    private static int getValueFromPropertiesAsInt(JsonNode modelProperties, String key) {
        return modelProperties.get(key).intValue();
    }
}
